<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/30 0030
 * Time: 下午 13:27
 */

namespace app\admin\model;

use app\admin\model\ProductTypes as A;
use think\Loader;
use think\Validate;
use think\Db;
use think\Model;
class Product extends Model
{
    protected  $pk='products_id';//主键
    protected $table = 'xcx_products';
    //增加分类
    public function add_goods($data)
    {
        //halt($data);
        $validate = Loader::validate('Product');

        if(!$validate->check($data)){
            return ['valid'=>0,'msg'=>$validate->getError()];
        }
        //判断名称是否唯一
        $name_yan = $this->where('products_name', $data['products_name'])->find();

        if ($name_yan['products_id'] != "") {
            return ['valid' => 0, 'msg' => '名称重复'];
            exit;
        }
        //判断产品编号是否唯一
        $number_yan = $this->where('products_number', $data['products_number'])->find();
        if ($number_yan['products_id']) {
            return ['valid' => 0, 'msg' => '产品编码重复'];
            exit;
        }
        $number='CLC1';
        $year=date('Y');
        $year=substr($year,-2);
        $spec=floor($data['products_specifications']/10);
        if(strlen($spec)<=2)
        {
            $spec='0'.$spec;
        }
        //产品系列表标号
         $types= new A();
        $numberType=$types->getTypeNumber($data['products_pid']);
        $pro_number=$number.$year.$numberType['type'].$numberType['series'].$spec.$data['products_number'];
        Db::startTrans();
        try{
            $arr['createtime'] = time();
            $arr['products_states'] = $data['data_btn'];
            $arr['products_sort'] = $data['products_sort'];
            $arr['products_name'] = $data['products_name'];
            $arr['products_introduction'] = $data['products_introduction'];
            $arr['products_pid'] = $data['products_pid'];

            $arr['products_number'] =$pro_number;
            $arr['products_marketprice'] = $data['products_marketprice'];
            $arr['products_sellingprice'] = $data['products_sellingprice'];
            $arr['products_stock']=$data['products_stock'];
            //标签
            $labeling = explode("/", $data['products_labeling']);
            $labedata = [];
            $labe = [];
            for ($i = 0; $i < count($labeling); $i++) {
                $labe[$i] = array(
                    'label_name' => $labeling[$i],
                    'createtime' => time()
                );
                $labedata[$i] = db('product_label')->insertGetId($labe[$i]);
            }
            //halt($labedata);
            $labestring = implode(",", $labedata);
            $arr['products_labeling'] = $labestring;
            //商品图片
            $imgdata = [];
            for ($i = 0; $i < count($data['img']); $i++) {
                $img[$i] = array(
                    'pimg_url' => $data['img'][$i],
                    'createtime' => time()
                );
                $imgdata[$i] = db('product_img')->insertGetId($img[$i]);
            }
            $imgstring = implode(",", $imgdata);
            $arr['products_pictureset'] = $imgstring;
            //商品规格
            $arr['products_specifications'] = $data['products_specifications'];
            //商品详情图
            $detailsdata = array(
                'pdetails_url' => $data['content'],
                'createtime' => time()
            );
            $details= db('product_details')->insertGetId($detailsdata);
            $arr['products_details'] = $details;
            //判断是否为外来注册
            //halt($user_yan);
            $result = $this->save($arr);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['valid'=>1,'msg'=>'添加失败'];
        }
            return ['valid'=>4,'msg'=>'添加成功'];
    }
    public function edit_goods($data)
    {
        //halt($data);
        $validate = Loader::validate('Product');

        if(!$validate->check($data)){
            return ['valid'=>0,'msg'=>$validate->getError()];
        }
        //判断名称是否唯一
        $name_yan = $this->where('products_name', $data['products_name'])->value('products_id');

        if ($name_yan !=$data['products_id']) {
            return ['valid' => 0, 'msg' => '名称重复'];
            exit;
        }
        //判断产品编号是否唯一
        $number_yan = $this->where('products_number', $data['products_number'])->value('products_id');
        if ($name_yan !=$data['products_id']) {
            return ['valid' => 0, 'msg' => '产品编码重复'];
            exit;
        }
        Db::startTrans();
        try{
            $arr['createtime'] = time();
            $arr['products_states'] = $data['data_btn'];
            $arr['products_sort'] = $data['products_sort'];
            $arr['products_name'] = $data['products_name'];
            $arr['products_introduction'] = $data['products_introduction'];
            $arr['products_pid'] = $data['products_pid'];

            $arr['products_number'] =$data['products_number'];
            $arr['products_marketprice'] = $data['products_marketprice'];
            $arr['products_sellingprice'] = $data['products_sellingprice'];
            $arr['products_stock']=$data['products_stock'];
            //标签
            $labeling = explode("/", $data['products_labeling']);
            $labedata = [];
            $labe = [];
            for ($i = 0; $i < count($labeling); $i++) {
                $labe[$i] = array(
                    'label_name' => $labeling[$i],
                    'createtime' => time()
                );
                $labedata[$i] = db('product_label')->insertGetId($labe[$i]);
            }
            //halt($labedata);
            $labestring = implode(",", $labedata);
            $arr['products_labeling'] = $labestring;
            //商品图片
            $imgdata = [];
            for ($i = 0; $i < count($data['img']); $i++) {
                $img[$i] = array(
                    'pimg_url' => $data['img'][$i],
                    'createtime' => time()
                );
                $imgdata[$i] = db('product_img')->insertGetId($img[$i]);
            }
            $imgstring = implode(",", $imgdata);
            $arr['products_pictureset'] = $imgstring;
            //商品规格
            //$arr['products_specifications'] = $data['products_specifications'];
            //商品详情图
            $detailsdata = array(
                'pdetails_url' => $data['content'],
                'createtime' => time()
            );
            $details= db('product_details')->insertGetId($detailsdata);
            $arr['products_details'] = $details;
            //判断是否为外来注册
            //halt($user_yan);
            $result = $this->allowField(true)->save($arr,['products_id'=>$data['products_id']]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['valid'=>1,'msg'=>'添加失败'];
        }
            return ['valid'=>4,'msg'=>'添加成功'];
    }
    //查询商品
    public function getAllData($state)
    {
        //$res=$this->where('products_states',$state)->select();
        $res=Db::table('xcx_products')
            ->alias('a')
            ->join('product_place p','a.products_id=p.product_id','LEFT')
            //->where('products_states',$state)
            ->select();
        return $res;
    }
    //查询商品名称
    public function getProductName($products_id,$name)
    {
         $res=$this->where('products_id',$products_id)->field("products_id,$name,products_specifications,products_specifi")->find();
         return $res;
    }
    //添加商品规格元素
    public function add_specific($data)
    {
        //halt($data);
        if (!$data['token']) {
            return ['valid' => 0, 'msg' => '请输入产品规格'];
            exit;
        }
        $getData = [];
        for ($i = 1; $i <= $data['tokenMax']; $i++) {
            if (isset($data['type' . $i])) {
                $getData[$i]['pspecifications_type'] = $data['type' . $i][0];
                $getData[$i]['pspecifications_element'] = json_encode($data['speci' . $i]);
                if (isset($data['img' . $i]) && $data['img' . $i]) {
                    $getData[$i]['pspecifications_img'] = json_encode($data['img' . $i]);
                }
            }
        }
        //halt($getData);
        $getKey = [];
        for ($i = 1; $i <= $data['tokenMax']; $i++) {

            if (isset($getData[$i])) {
                $getData[$i]['pspecifications_states'] = 1;
                $getData[$i]['createtime'] = time();
                //halt($getData);
                $result = db('product_specifications')->insertGetId($getData[$i]);
                if (false === $result) {
                    // 验证失败 输出错误信息
                    return ['valid' => 1, 'msg' => "'添加'.$getData[$i]['pspecifications_type'].失败"];
                }
                $getKey[$i] = $result;
            }
        }
        if ((max($getKey) - min($getKey) + 1) != $data['token']) {
            return ['valid' => 1, 'msg' => "'添加规格失败"];
        }
        $updataSpecific = array(
            'products_specifications' => implode(',', $getKey)
        );
        $getProductSpecif = $this->save($updataSpecific, ['products_id' => $data['products_id']]);
        if (false === $getProductSpecif) {
            // 验证失败 输出错误信息
            return ['valid' => 1, 'msg' => "添加规格元素失败"];
        } else {
            return ['valid' => 4, 'msg' => "添加规格元素成功"];
        }
    }
    //获得规格信息
    public function getSpecifiData($products_id)
    {
        $specifiAll=$this->getProductName($products_id,'products_specifications');
        $specifiAll=explode(',',$specifiAll['products_specifications']);
        $count=count($specifiAll);
        $data=db('product_specifications')->whereIn('pspecifications_id',$specifiAll)->select();
        $getData=[];
        //halt($data);
        $a=[];
        $pspecifImg=[];
        for($k=0;$k<count($data);$k++)
        {
            $getData[$k]=json_decode($data[$k]['pspecifications_element']);
            if(strpos($data[$k]['pspecifications_img'],'.'))
            {
                $pspecifImg=json_decode($data[$k]['pspecifications_img']);
            }else
                {
                    $pspecifImg=json_decode($data[$k]['pspecifications_img']);
                }

        }
        if(count($getData)==1)
        {
            for ($j = 0; $j < count($getData[0]); $j++) {
                $a[$j]=array(
                    'pspecif'=> array($getData[0][$j]),
                    'pspeci_element'=>json_encode(array($getData[0][$j])),
                    'pspecifImg'=>$pspecifImg[$j],
                    'pspeci_snapshot'=>json_encode(array($data[0]['pspecifications_type'] => $getData[0][$j]))
                );
            }
        }else if(count($getData)==2)
        {
            for($i=0;$i<count($getData[0]);$i++)
            {
                for($j=0;$j<count($getData[1]);$j++)
                {
                    $a[$i.'-'.$j]=array(
                           'pspecif'=> array($getData[0][$i], $getData[1][$j]),
                        'pspeci_element'=>json_encode(array($getData[0][$i],$getData[1][$j])),
                        'pspecifImg'=>$pspecifImg[$i],
                        'pspeci_snapshot'=>json_encode(array($data[0]['pspecifications_type'] => $getData[0][$i], $data[1]['pspecifications_type'] => $getData[1][$j]))
                        );
                }
            }
        }else if(count($getData)==3)
        {
            for($i=0;$i<count($getData[0]);$i++)
            {
                for($j=0;$j<count($getData[1]);$j++)
                {
                    for($k=0;$k<count($getData[2]);$k++) {
                        $a[$i.'-'.$j.'-'.$k]= array(
                            'pspecif'=> array($getData[0][$i], $getData[1][$j], $getData[2][$k]),
                            'pspeci_element'=>json_encode(array($getData[0][$i],$getData[1][$j],$getData[2][$k])),
                            'pspecifImg'=>$pspecifImg[$i],
                            'pspeci_snapshot'=>json_encode(array($data[0]['pspecifications_type'] => $getData[0][$i], $data[1]['pspecifications_type'] => $getData[1][$j], $data[2]['pspecifications_type'] => $getData[2][$k])),
                        );
                    }
                }
            }
        }else if(count($getData)==4)
        {
            for($i=0;$i<count($getData[0]);$i++)
            {
                for($j=0;$j<count($getData[1]);$j++)
                {
                    for($k=0;$k<count($getData[2]);$k++)
                    {
                        for($h=0;$k<count($getData[3]);$h++)
                        {
                            $a[$i.'-'.$j.'-'.$k.'-'.$h]=array(
                                'pspecif'=> array($getData[0][$i],$getData[1][$j],$getData[2][$k],$getData[3][$h]),
                                'pspeci_element'=>json_encode(array($getData[0][$i],$getData[1][$j],$getData[2][$k],$getData[3][$h])),
                                'pspecifImg'=>$pspecifImg[$i],
                                'pspeci_snapshot'=>json_encode(array($data[0]['pspecifications_type']=>$getData[0][$i],$data[1]['pspecifications_type']=>$getData[1][$j],$data[2]['pspecifications_type']=>$getData[2][$k],$data[3]['pspecifications_type']=>$getData[3][$h]))

                            );
                        }

                    }
                }
            }
        }

        //halt($getData);
        //halt($a);
        $res=array(
            'count'=>$count,
            'data'=>$data,
            'a'=>$a
        );
        return $res;
    }
    //添加规格集合
    public function add_prdspecific($data)
    {
        //halt($data);
        $getData=[];
        for($i=0;$i<count($data['pspeci_element']);$i++)
        {
            $getData[$i]['pspeci_element']=$data['pspeci_element'][$i];
            $getData[$i]['pspeci_snapshot']=$data['pspeci_snapshot'][$i];
            $getData[$i]['pspeci_price']=$data['pspeci_price'][$i];
            $getData[$i]['pspeci_stock']=$data['pspeci_stock'][$i];
            $getData[$i]['pspeci_img']=$data['pspecifImg'][$i];
        }
        $getKey=[];
        for($i=0;$i<count($getData);$i++)
        {
            $getData[$i]['createtime']=time();
            $getData[$i]['pspeci_states']=1;
            $res=db('product_speci')->insertGetId($getData[$i]);
            $getKey[$i]=$res;
        }
        $updataSpecific = array(
            'products_specifi' => implode(',', $getKey)
        );
        $getProductSpecif = $this->save($updataSpecific, ['products_id' => $data['products_id']]);
        if (false === $getProductSpecif) {
            // 验证失败 输出错误信息
            return ['valid' => 1, 'msg' => "添加规格集合失败"];
        } else {
            return ['valid' => 4, 'msg' => "添加规格集合成功"];
        }
    }
    //获得提交后的产品规格
    public function getSpecifiIndex($id)
    {
        $res=$this->where('products_id',$id)->field("products_specifi,products_specifications")->find();
        $res['comm']=db('product_specifications')->whereIn('pspecifications_id',explode(',',$res['products_specifications']))->field('pspecifications_type')->select();
        $res['count']=count(explode(',',$res['products_specifications']));
            $data=db("product_speci")->whereIn("pspeci_id",explode(',',$res['products_specifi']))->select();
        foreach ($data as $k=>$v)
        {
            $v['pspeci_element']=json_decode($v['pspeci_element'],true);
            $v['pspeci_snapshot']=json_decode($v['pspeci_snapshot'],true);
            $data[$k]=$v;
        }
        $data=array(
            'res'=>$res,
            'data'=>$data
        );
        return $data;
    }
    //修改
   public function editSpr($data,$name)
   {
       $result=db('product_speci')->where('pspeci_id',$data['id'])->update([$name=>$data['value']]);
       if(false === $result){
           // 验证失败 输出错误信息
           return ['valid'=>1,'msg'=>'修改失败'];
       }else{
           return ['valid'=>4,'msg'=>'修改成功'];
       }
   }
   //删除
   public function deleteInfo($data)
   {
       $result=db('product_speci')->where('pspeci_id',$data['id'])->delete();
       if(false === $result){
           // 验证失败 输出错误信息
           return ['valid'=>1,'msg'=>'删除失败'];
       }else{
           return ['valid'=>4,'msg'=>'删除成功'];
       }
   }

    public function shelf($data)
    {

        $pspeci_states=db('product_speci')->where('pspeci_id',$data['id'])->value('pspeci_states');

        if($pspeci_states==1)
        {
            $result=db('product_speci')->where('pspeci_id',$data['id'])->update(['pspeci_states'=>0]);
        }else
            {
                $result=db('product_speci')->where('pspeci_id',$data['id'])->update(['pspeci_states'=>1]);
            }
        if(false === $result){
            // 验证失败 输出错误信息
            return ['valid'=>1,'msg'=>'操作失败'];
        }else{
            return ['valid'=>4,'msg'=>'操作成功'];
        }
    }
    //获得分类下的产品
    public function  getTypeProducts($data)
    {
        $res=$this->where('products_pid',$data['id'])->field('products_name,products_id')->select();
        return $res;
    }
    //获得分类信息
    public function getProducts($id)
    {
        $product=Db::table('xcx_products')
            ->alias('p')
            ->where('products_id',$id)
            ->where('products_states',1)
            //->field('c.recommend_id,c.classi_id,c.recommend_img,c.classi_text,p.products_sellingprice,p.products_name,p.products_introduction')
            ->find();
        //图片/标签/详情
        $product['img']=db('product_img')->whereIn('pimg_id',explode(',',$product['products_pictureset']))->select();
        $product['detail']=db('product_details')->where('pdetails_id',$product['products_details'])->find();
        $biaoq =db('product_label')->whereIn('label_id',explode(',',$product['products_labeling']))->select();
        $product['biaoq']="";
        foreach($biaoq as $v)
        {
            $product['biaoq'] =$product['biaoq'].'/'.$v['label_name'];
        }
        $product['biaoq']=ltrim($product['biaoq'],"/");
        return $product;
        //halt($product);

    }
    //提交下架信息
    public function updateReason($data)
    {
        $pspeci_states=$this->where('products_id',$data['id'])->value('products_states');

        if($pspeci_states==1)
        {
            $result=$this->where('products_id',$data['id'])->update(['products_states'=>0,'products_upshelfreason'=>$data['form'],'update_time'=>time()]);
        }
        if(false === $result){
            // 验证失败 输出错误信息
            return ['valid'=>1,'msg'=>'操作失败'];
        }else{
            return ['valid'=>4,'msg'=>'操作成功'];
        }
    }
    public function faShow($id)
    {
        $pspeci_states=$this->where('products_id',$id)->value('products_states');
        if($pspeci_states==0)
        {
            $result=$this->where('products_id',$id)->update(['products_states'=>1]);
        }
        if(false === $result){
            // 验证失败 输出错误信息
            return ['valid'=>1,'msg'=>'操作失败'];
        }else{
            return ['valid'=>4,'msg'=>'操作成功'];
        }
    }
}